use uuid::Uuid;

use async_graphql::{Error, ErrorExtensions};
use rbatis::crud::CRUD;
use rbatis::rbatis::Rbatis;

use crate::features::users::modelsdbo::{NewUser, UserDBO};
use crate::features::users::modelsgqo::User;
use crate::features::users::repository::{self};
use crate::util::constant::GqlResult;
// 查询所有用户
pub async fn all_users(rbatis_pool: &Rbatis) -> Vec<UserDBO> {
  let users = rbatis_pool.fetch_list::<UserDBO>().await.unwrap();

  users
}

// 插入新用户
pub async fn new_user(rbatis_pool: &Rbatis, mut new_user: NewUser) -> GqlResult<User> {
  new_user.email = new_user.email.to_lowercase();

  if repository::get_user_by_email(rbatis_pool, &new_user.email)
    .await
    .is_ok()
  {
    Err(Error::new("email 已存在").extend_with(|_, e| e.set("details", "1_EMAIL_EXIStS")))
  } else {
    new_user.cred = "P38V7+1Q5sjuKvaZEXnXQqI9SiY6ZMisB8QfUOP91Ao=".to_string();

    let my_uuid = Uuid::new_v4();

    new_user.id = my_uuid.to_simple().to_string();

    // rbatis_pool
    //  .save(&new_user)
    //  .await
    //  .expect("插入 user 数据时出错");

    let user_dbo = repository::get_user_by_email(rbatis_pool, &new_user.email).await;

    if user_dbo.is_ok() {
      Ok(user_dbo.unwrap().into())
    } else {
      Err(Error::new("User Saved Failed").extend_with(|_, e| e.set("details", "User Table Error")))
    }
  }
}
